package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.dto.CancelDto;
import com.zzyl.nursing.dto.NursingTaskDto;
import com.zzyl.nursing.dto.doTaskDto;
import com.zzyl.nursing.dto.updateTimeTaskDto;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.INursingTaskService;
import com.zzyl.nursing.vo.NursingTaskDetailVo;
import com.zzyl.nursing.vo.NursingTaskVo;
import com.zzyl.system.mapper.SysUserMapper;
import com.zzyl.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 护理任务Service业务层处理
 *
 * @author Nuyoah
 * @date 2025-06-02
 */
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;

    @Autowired
    private IElderService elderService;

    @Autowired
    private ICheckInService checkInService;
    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskDetailVo selectNursingTaskById(Long id) {
        NursingTaskDetailVo vo = new NursingTaskDetailVo();
        NursingTask nursingTask = this.getById(id);
        BeanUtils.copyProperties(nursingTask, vo);
        // 获取老人年龄信息
        Elder elder = elderService.selectElderById(Long.valueOf(nursingTask.getElderId()));
        vo.setAge( elder.getAge());
        //性别
        vo.setSex(elder.getSex()==0?"女":"男");

        //获取执行人
        if(StringUtils.isNotEmpty(nursingTask.getUpdateBy())){
            SysUser sysUser = sysUserService.selectUserById(Long.valueOf(nursingTask.getUpdateBy()));
            vo.setUpdater(sysUser.getNickName());
        }

        //获取护理任务的创建人id
        vo.setUpdater( sysUserService.selectUserById(Long.valueOf(nursingTask.getCreateBy())).getNickName());

        String nursingId = nursingTask.getNursingId();
        List<Long> userIds = new ArrayList<>();
        if ( StringUtils.isNotEmpty(nursingId)){
            String[] split = nursingId.split(",");
            for (String s : split) {
                 userIds.add(Long.valueOf(s));
            }
        }
        //根据护理员ID获取护理员姓名
        List<String> nursingNameList = new ArrayList<>();
        userIds.forEach(userId -> {
            nursingNameList.add(sysUserService.selectUserById(userId).getNickName());
        });
        vo.setNursingName(nursingNameList);

        //获取护理等级名称
        CheckIn checkIn = checkInService.getOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getElderId, nursingTask.getElderId()));
        vo.setNursingLevelName(checkIn.getNursingLevelName());

        return vo;
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {
        return save(nursingTask) ? 1 : 0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask) {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private ISysUserService sysUserService;
     @Autowired
     private SysUserMapper sysUserMapper;

    /**
     * 获取护理任务列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<NursingTaskVo> nursingTaskList(NursingTaskDto dto) {
        Page<NursingTask> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        //执行sql
        List<NursingTask> nursingTasks = nursingTaskMapper.selectByPage(dto);

        Set<Long> userIds = new HashSet<>();
        //拼装护理员列表ID
        nursingTasks.forEach(nursingTask ->{
            if(StringUtils.isNotEmpty(nursingTask.getNursingId())){
                String[] split = nursingTask.getNursingId().split(",");
                for (String nid : split) {
                    userIds.add(Long.valueOf(nid));
                }
            }
        });

        page.setRecords(nursingTasks);
        List<NursingTaskVo> nursingTaskVoList = page.getRecords().stream().map(x -> {
            NursingTaskVo nursingTaskVo = new NursingTaskVo();
            BeanUtils.copyProperties(x, nursingTaskVo);
            nursingTaskVo.setCreateTime(x.getCreateTime().toString());
            nursingTaskVo.setEstimatedServerTime(x.getEstimatedServerTime().toString());
            nursingTaskVo.setProjectId(Integer.valueOf(x.getProjectId()));
            nursingTaskVo.setProjectName(x.getProjectName());
            nursingTaskVo.setElderId(Long.valueOf(Integer.valueOf(x.getElderId())));
            nursingTaskVo.setNursingId(userIds.toString());
            //根据护理员ID获取护理员姓名
            List<String> nursingNameList = new ArrayList<>();
            userIds.forEach(userId -> {
                nursingNameList.add(sysUserService.selectUserById(userId).getNickName());
            });
            nursingTaskVo.setNursingName(String.valueOf(nursingNameList));
            return nursingTaskVo;
        }).collect(Collectors.toList());

        Page<NursingTaskVo> voPage = new Page<>();
        voPage.setRecords(nursingTaskVoList);
        voPage.setTotal(page.getTotal());
        return voPage;
    }

    /**
     * 取消任务
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(CancelDto dto) {
        this.lambdaUpdate()
                .eq(NursingTask::getId, dto.getTaskId())
                .set(NursingTask::getCancelReason, dto.getReason())
                .set(NursingTask::getStatus, 3)
                .update();
    }

    /**
     * 执行任务
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doTask(doTaskDto dto) {
        //查询护理任务
        NursingTask nursingTask = getById(dto.getTaskId());
        //修改任务
        if (ObjectUtil.isEmpty(nursingTask)) {
            throw new BaseException("护理任务不存在");
        }
        nursingTask.setStatus(2);
        nursingTask.setRealServerTime(dto.getEstimatedServerTime());
        nursingTask.setTaskImage(dto.getTaskImage());
        nursingTask.setMark(dto.getMark());
        updateById(nursingTask);
    }

    /**
     * 任务改期
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTimeTask(updateTimeTaskDto dto) {
        this.lambdaUpdate()
                .eq(NursingTask::getId, dto.getTaskId())
                .set(NursingTask::getEstimatedServerTime, dto.getEstimatedServerTime())
                .update();
    }
}
